<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

class GaController extends Controller
{

  public function qrcode()
  {
    $ga = new \PHPGangsta_GoogleAuthenticator();
    $user = auth()->user();

    if (!$user->google_secret) {
      $user->google_secret = $ga->createSecret();
      $user->save();
    }

    $qrCodeUrl = $ga->getQRCodeGoogleUrl("FCB-{$user->id}", $user->google_secret);
    return success($qrCodeUrl);
  }

  public function getCode()
  {
    $ga = new \PHPGangsta_GoogleAuthenticator();
    $user = auth()->user();
    $user->google_secret = $ga->createSecret();
    $user->save();

    return $ga->getCode($user->google_secret);
  }

  public function bind(Request $request)
  {
    $ga = new \PHPGangsta_GoogleAuthenticator();
    $user = auth()->user();

    if (!$ga->verifyCode($user->google_secret, $request->code, 2)) {
      fail('验证失败');
    }

    $user->update([
      'google_auth_enable' => $request->bind
    ]);

    return success('ok');
  }

  public function destroy($id)
  {
    $user = User::findOrFail($id);
    $user->google_secret = null;
    $user->google_auth_enable = false;
    $user->save();
    return success('ok');
  }
}
